﻿<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>client 1.0</title>
    <script src="js/jquery-3.6.0.slim.min.js"></script>
    <script>
        var socket;

        $(function () {
            
        });

        function send() {
            if (!socket || socket.readyState !== WebSocket.OPEN) {
                alert("socket not connected");
                return;
            }

            var message = $("#message").val();
            var userid = $("#userid").val();
            var json = { "action": "send_to_all", "fromUserId": userid, "content": message, "sendTime": nowDateTime() };
            var jsonstr = JSON.stringify(json);
            socket.send(jsonstr);
            echo("client:" + message);

        };

        function connect() {
            socket = new WebSocket("ws://192.168.2.56:8083/ws");
            socket.onopen = function (event) {
                echo("open");
                document.getElementById("userid").disabled = "disabled";
                document.getElementById("connect").disabled = "disabled";

                document.getElementById("send").disabled = "";
                document.getElementById("message").disabled = "";
            };
            socket.onclose = function (event) {
                echo("close");
            };
            //socket.onerror = updateState;
            socket.onmessage = function (event) {
                echo("server:" + event.data);
            };
        };

        function echo(str) {
            document.getElementById("container").innerHTML = document.getElementById("container").innerHTML + str + "<br />";
            console.log(str);
        }

        function nowDateTime() {
            var myDate = new Date();
            return myDate.toLocaleDateString() + " " + myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds();
        }
    </script>
</head>
<body>
    <input type="text" name="userid" id="userid" value="" placeholder="userid" />
    <input type="button" name="connect" id="connect" value="连接" onclick="connect();" />
    <input type="text" name="message" id="message" value="" placeholder="message" />
    <input type="button" name="send" id="send" value="send" onclick="send();" />
    <div id="container"></div>
</body>
</html>